﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Web.UI;
using System.IO;
using System.Text;

using RexToy.Logging;
using RexToy.Template;
using RexToy.ExpressionLanguage;
using RexToy.UI.Web.Configuration;

namespace RexToy.UI.Web.Tags
{
    public class Tag : Control
    {
        private static ILog _log = LogContext.GetLogger<Tag>();

        public Tag()
        {
            this.EnableViewState = false;
        }

        private string _tagPath;
        public string TagPath
        {
            get { return _tagPath; }
            set { _tagPath = value; }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            Assertion.IsFalse(string.IsNullOrEmpty(_tagPath), "Tag path not set.");

            string physicalPath = MapPathSecure(Path.Combine(ResolveUrl(WebConfig.WebConfiguration.TagPath)));
            var ctx = new WebTagContext();
            var elcfg = new ExpressionLanguageEngineConfig(EvalExceptionHandlingPolicy.IgnorePolicy, string.Empty, WebConfig.WebConfiguration.ELCache);
            var tEngine = TemplateEngine.CreateInstance(physicalPath, ctx, WebConfig.WebConfiguration.TemplateASTCache, elcfg);

            try
            {
                string result = tEngine.Render(_tagPath);
                writer.Write(result);
            }
            catch (Exception ex)
            {
                writer.Write("[Tag render fail.]");
                _log.Error(string.Format("Tag {0} render error:\n{1}", _tagPath, ex.ToString()));
                WriteDetail(writer, ex);
            }
        }

        [Conditional("DEBUG")]
        private void WriteDetail(HtmlTextWriter writer, Exception ex)
        {
            StringBuilder str = new StringBuilder();
            while (ex != null)
            {
                if (!(ex is System.Reflection.TargetInvocationException))
                    str.AppendFormat("{0}----", ex.Message);
                ex = ex.InnerException;
            }
            writer.Write(str.ToString().TrimEnd('-'));
        }
    }
}
